<template>
  <a-modal
      :confirmLoading="confirmLoading"
      :destroyOnClose="true"
      :maskClosable="false"
      :title="title"
      :visible="visible"
      :width="720"
      @cancel="handleCancel"
      @ok="handleSubmit"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="品牌名称">
          <a-input
              v-decorator="['brandName', { rules: [{ required: true, min: 2, message: '请输入至少2个字符' }] }]"
              placeholder="请输入品牌名称"
          />
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="品牌logo">
          <SelectImage v-decorator="['logo', { rules: [{ required: true, message: '请至少上传1张商品图片'  }] }]"/>
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="品牌描述">
          <a-textarea
              v-decorator="['description']"
              :autoSize="{ minRows: 4 }"
              placeholder="请输入品牌描述内容 (300个字符以内)"
          />
        </a-form-item>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import * as Api from '@/api/brand'
import SelectImage from "@/components/SelectImage/SelectImage.vue";

export default {
  components: {
    SelectImage
  },
  data() {
    return {
      // 对话框标题
      title: '',
      // 标签布局属性
      labelCol: {
        span: 7
      },
      // 输入框布局属性
      wrapperCol: {
        span: 13
      },
      // modal(对话框)是否可见
      visible: false,
      // modal(对话框)确定按钮 loading
      confirmLoading: false,
      // 当前表单元素
      form: this.$form.createForm(this),
    }
  },
  methods: {

    // 显示对话框
    add() {
      // 显示窗口
      this.title = '新增记录'
      this.visible = true
    },

    // 确认按钮
    handleSubmit(e) {
      e.preventDefault()
      // 表单验证
      const {form: {validateFields}} = this
      validateFields((errors, values) => {
        // 提交到后端api
        !errors && this.onFormSubmit(values)
      })
    },

    // 关闭对话框事件
    handleCancel() {
      this.visible = false
      this.form.resetFields()
    },

    // 提交到后端api
    onFormSubmit(values) {
      this.confirmLoading = true
      Api.add(values)
          .then(result => {
            // 显示成功
            this.$message.success('操作成功', 1.5)
            // 关闭对话框事件
            this.handleCancel()
            // 通知父端组件提交完成了
            this.$emit('handleSubmit', values)
          })
          .finally(result => {
            this.confirmLoading = false
          })
    }

  }
}
</script>
